import { useConfig } from "../../hook/D8dConfigProvider.tsx";
import { useApiRequest } from "../../hook/useApiRequest.ts";
import type { TPageRequest } from "../../global.ts";
import { Form, TreeSelect } from "antd";
import { useEffect, useMemo, useState } from "react";

interface TreeSelectOption {
  id: number | string;
  pId: number | string;
  title: string;
  value: number | string;
  rootPId?: string;
}

interface FieldIdentifier {
  pId: string;
  title: string;
}

interface Props {
  treeApiUrl?: string; // 树列表API
  fieldIdentifier?: FieldIdentifier; // 字段标识
  value?: any;
  onChange?: (values: any) => void;
  multiple?: boolean;
}

export default function AdminTreeSelect({
  value,
  onChange,
  treeApiUrl,
  fieldIdentifier,
  multiple = false,
}: Props) {
  const { token } = useConfig();
  const { requestWithToken } = useApiRequest();
  const [asyncData, setAsyncData] = useState<TreeSelectOption[]>([]);
  const form = Form.useFormInstance();

  const newValue = useMemo(() => {
    if (multiple) {
      if (typeof value === "string") {
        try {
          return JSON.parse(value);
        } catch (error) {}
      }
    }
    return value;
  }, [multiple,value]);

  const loadMenu = async () => {
    if (!treeApiUrl) return;

    if (token) {
      const query: TPageRequest = {
        sort: ["updated_at:desc"],
        pagination: { page: 1, pageSize: 50 },
        filters: {}, //上级ID: { $eq: 上级ID }, 级别: { $eq: 级别 }
        // fields: [
        //   "user_id",
        //   "app_pid",
        //   "app_id",
        //   "app_cover",
        //   "app_name",
        //   "application._create",
        //   "application._update",
        // ],
      };

      if (value !== undefined && fieldIdentifier?.pId) {
        (query.filters as any)[fieldIdentifier?.pId] = { $eq: value };
      }

      try {
        const result = await requestWithToken({
          url: treeApiUrl,
          method: "GET",
          data: query,
        });

        let deptList = asyncData;
        if (!deptList?.length)
          deptList = [
            {
              id: 0,
              pId: "",
              title: "/",
              value: 0,
            },
          ];

        if ((result?.code === 200 || result?.success) && fieldIdentifier) {
          result.data.map(
            (item: any) =>
              (deptList = deptList.concat({
                id: item?._id || item?.id,
                pId: parseInt(item[fieldIdentifier?.pId]),
                title: item[fieldIdentifier?.title],
                value: item?._id || item?.id,
                //isLeaf:item._id > 1
              }))
          );
          setAsyncData(deptList);
        }
      } catch (error) {
        console.error(error);
      }
    }
  };

  useEffect(() => {
    loadMenu();
  }, []);

  return (
    <TreeSelect
      placeholder="请选择"
      treeDataSimpleMode
      value={newValue}
      treeData={asyncData}
      onChange={onChange}
      allowClear
      multiple={multiple}
    />
  );
}
